package com.mediacloud.app.newsmodule.activity;

import android.content.Context;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;

import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chinamcloud.audioserver.APSHelper;
import com.chinamcloud.audioserver.MusicEntity;
import com.chinamcloud.audioserver.TaskAudioConfig;
import com.chinamcloud.collect.AcquisitionManager;
import com.chinamcloud.report.ReportKit;
import com.mediacloud.app.appfactory.cache.UserRecommend;
import com.mediacloud.app.assembly.util.DateParse;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.cloud.ijkplayersdk.auth.AuthMode;
import com.mediacloud.app.cloud.ijkplayersdk.auth.URLAuth;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleItemReciver;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.LiveProgramListReciver;
import com.mediacloud.app.model.news.LiveProgramListReciver.ProgramWeekItem;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.model.news.ProgramListItem.GuideItemState;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast;
import com.mediacloud.app.newsmodule.fragment.audio.live.AudioLiveProgramTable;
import com.mediacloud.app.newsmodule.utils.AddIntegralCounter;
import com.mediacloud.app.newsmodule.utils.AddMedalStatistics;
import com.mediacloud.app.newsmodule.utils.Addintegral;
import com.mediacloud.app.newsmodule.utils.DomainUtil;
import com.mediacloud.app.newsmodule.utils.KillMusicUtils;
import com.mediacloud.app.newsmodule.utils.LiveMediaPlayBackInvoker;
import com.mediacloud.app.newsmodule.utils.NewsDetailInvoker;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.VideoLiveProgramListInvoker;
import com.mediacloud.app.newsmodule.view.BaseSpiderView;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.mediacloud.app.user.model.UserInfo;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 音频直播类
 *
 * @author x
 */
public class AudioLiveDetailActivityHalf extends BaseAudioActivityHalf implements LiveReplayBroadcast.LiveReplayHandle, LiveReplayBroadcast.ToggleHandle {
    //节目单数据
    protected List<ProgramWeekItem> programListItems;
    //取节目单用的
    protected VideoLiveProgramListInvoker liveProgramListInvoker;
    //节目单
    protected AudioLiveProgramTable audioLiveProgramTable;
    //节目单的view
    protected View programView;
    private Animation showAnimation;
    protected LiveReplayBroadcast liveReplayBroadcast;
    protected NewsDetailInvoker newsDetailInvoker;
    protected AudioDetailCallBack audioDetailCallBack;
    protected ProgramListCallBack programListCallBack;
    protected String url;
    protected LiveMediaPlayBackInvoker liveMediaPlayBackInvoker;
    protected LivePlayBackUrlReciver livePlayBackUrlReciver;
    private boolean firstOpen = true;
    protected long startLong = 0L;
    protected long endLong = 0L;

    public boolean hasChatRoom() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (!hasChatRoom()) {
            //不是子类 那个聊天室的直播 需要处理这些View
            ViewGroup.LayoutParams layoutParams = streamLineBtn.getLayoutParams();
            layoutParams.width = dp2px(this, 27).intValue();
            layoutParams.height = dp2px(this, 31).intValue();
            streamLineBtn.setLayoutParams(layoutParams);
            streamLineBtn.setText("");
            streamLineBtn.setBackgroundResource(R.drawable.icon_program);
            loopModeBtn.setVisibility(View.GONE);
        }

        initBroad();
        audioDetailCallBack = new AudioDetailCallBack();
        newsDetailInvoker = new NewsDetailInvoker(audioDetailCallBack);
        livePlayBackUrlReciver = new LivePlayBackUrlReciver();
        liveMediaPlayBackInvoker = new LiveMediaPlayBackInvoker(livePlayBackUrlReciver);
        getAudioDetail();
        onPageStart();
    }


    @Override
    public void finish() {
        super.finish();
        if(apsKit.isPlaying()){
            if(apsKit.isTaskPlaying()){
                TaskAudioConfig config = new TaskAudioConfig(false, 0, 0);
                APSHelper.saveTaskConfig("" + articleItem.getId(),config);
            }
            sendShowFloaWinMsg();
        }else{
            KillMusicUtils.hideReadNewsWin();
        }
        if (liveProgramListInvoker != null)
            liveProgramListInvoker.destory();
        liveProgramListInvoker = null;
        if (newsDetailInvoker != null)
            newsDetailInvoker.destory();
        newsDetailInvoker = null;
        if (liveReplayBroadcast != null && liveReplayBroadcast.registed) {
            liveReplayBroadcast.registed = false;
            LocalBroadcastManager.getInstance(this).unregisterReceiver(liveReplayBroadcast);
        }
    }

    protected void onAudioDetailCallBack(ArticleItemReciver data) {

    }

    @Override
    public void toggle() {
        apsKit.toggle();
    }

    class AudioDetailCallBack implements DataInvokeCallBack<ArticleItemReciver> {
        @Override
        public void success(ArticleItemReciver data) {
            if (data.state) {
                onAudioDetailCallBack(data);
                if (TextUtils.isEmpty(articleItem.getSummary())) {
                    setCl_lyaoutVisiable(View.GONE);
                } else {
                    setCl_lyaoutVisiable(View.VISIBLE);
                    audioDes.setText(articleItem.getSummary());
                }
                tvPlayCount.setText(StringUtils.toTenThousand(articleItem.getHitCount_format()) + "播放");
                if (TextUtils.isEmpty(articleItem.getAuthor())) {
                    tvAuthor.setVisibility(View.GONE);
                } else {
                    tvAuthor.setVisibility(View.VISIBLE);
                    tvAuthor.setText(articleItem.getAuthor());
                }
                tvPublishData.setText(articleItem.getPublishdate_format());

                articleItem = data.articleItem;
                ReportKit.INSTANCE.escalationArticle(articleItem.getId()+"", articleItem.getTitle(),articleItem.getPublishdate(),articleItem.getAddUser());
                if (articleItem.getSpider() != null) {
                    BaseSpiderView spiderView = findViewById(R.id.spiderView);
                    spiderView.setDate(articleItem);
                }
                FunKt.load(logoView, articleItem.getLogo()
                        , 10, AppFactoryGlobalConfig.getDefaultImageLoadDrawable(), null);
                refreshBottomStyle(data.articleItem, 1);
                UserRecommend.addItemKeyWord(articleItem, AudioLiveDetailActivityHalf.this);

                if (TextUtils.isEmpty(articleItem.getGoodsID())) {
                    normalPayUtil.showPaidView();
                    optUrl();
                } else {
                    normalPayUtil.judgeShowPayView(articleItem);
                }
                startAddIntegralCounter();
                AddMedalStatistics.addMedalStatistics(AudioLiveDetailActivityHalf.this); //勋章统计


                //     getComponentData();
            } else {
                ToastUtil.show(AudioLiveDetailActivityHalf.this, R.string.noraml_newserror);
            }
            broccoliLayout.setVisibility(View.GONE);
            mErrorView.setVisibility(View.GONE);
        }

        @Override
        public void fault(Object data) {
            ToastUtil.show(AudioLiveDetailActivityHalf.this, R.string.noraml_newserror);
        }
    }

    private void startAddIntegralCounter() {
        AddIntegralCounter.start(this, new AddIntegralCounter.TimeoutCallback() {
            @Override
            public void timeoutCallback() {
                if (articleItem == null){
                    return;
                }
                Addintegral.addintegral(AudioLiveDetailActivityHalf.this, articleItem.getId(), 2, "1".equals(articleItem.getMovie().getIsStudyContent()) ? "1" : "0",articleItem);
            }
        });
    }

    @Override
    protected void onPaidAudio(String audio) {
        articleItem.setAudio(audio);
        optUrl();
    }


    protected void optUrl() {
        try {
            JSONObject video = new JSONObject(articleItem.getAudio());
            cdnEncrypt = video.optString("cdnConfigEncrypt");
            JSONArray tsAddress = null;
            if (video.has("ANDROID")) {
                tsAddress = video.optJSONArray("ANDROID");
            } else if (video.has("PC")) {
                tsAddress = video.optJSONArray("PC");
            }
            if(tsAddress == null){
                ToastUtil.show(this, R.string.noraml_newserror);
                return;
            }
            if (tsAddress.length() > 0) {
                JSONObject line = tsAddress.optJSONObject(0);
                url = line.optString("url");
                startPlay(url, articleItem);

            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "" + e.getMessage());
            ToastUtil.show(this, R.string.noraml_newserror);
        }
    }



    void initAnimation() {
        if (showAnimation != null)
            return;
        //暂时这样吧  平移参数要研究一下
        showAnimation = AnimationUtils.loadAnimation(this, R.anim.show_audio_program_animation);

    }

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1, -1);

    void showOrHide() {
        if (firstOpen) {
            ViewGroup parent = (ViewGroup) getWindow().getDecorView();
            if (programView.getParent() == null) {
                programView.setVisibility(View.GONE);
                parent.addView(programView, layoutParams);
            }
            firstOpen = false;
            Bundle bundle = new Bundle();
            bundle.putParcelable("data", articleItem);
            audioLiveProgramTable.setArguments(bundle);
            audioLiveProgramTable.setOnCloseBtnClickListenser(v -> {
                showAnimation.cancel();
                ViewGroup parent1 = (ViewGroup) programView.getParent();
                parent1.removeView(programView);
            });
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.audioLiveProgram, audioLiveProgramTable);
            transaction.show(audioLiveProgramTable);
            transaction.commitNowAllowingStateLoss();
            programView.setOnClickListener(v -> {
                showAnimation.cancel();
                ViewGroup parent12 = (ViewGroup) programView.getParent();
                parent12.removeView(programView);
            });
            getProgramList();
        } else {
            ViewGroup parentOld = (ViewGroup) programView.getParent();
            if (parentOld != null) parentOld.removeView(programView);
            programView.setVisibility(View.VISIBLE);
            ViewGroup parent = (ViewGroup) getWindow().getDecorView();
            if (programView.getParent() == null)
                parent.addView(programView, layoutParams);
            showAnimation.reset();
            programView.startAnimation(showAnimation);
        }
    }

    protected void initProgramList() {
        if (programView == null) {
            programListItems = null;
            audioLiveProgramTable = new AudioLiveProgramTable();
            Bundle bundle = new Bundle();
            bundle.putBoolean("fullScreen", false);
            audioLiveProgramTable.setArguments(bundle);
            programView = LayoutInflater.from(this).inflate(R.layout.aappfactory_audioliveprogram_popwin_half, null);
        }
    }

    protected void initBroad() {
        liveReplayBroadcast = new LiveReplayBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LiveReplayBroadcast.PlayAction);
        intentFilter.addAction(LiveReplayBroadcast.ToggleAction);
        liveReplayBroadcast.registed = true;
        LocalBroadcastManager.getInstance(this).registerReceiver(liveReplayBroadcast, intentFilter);
        liveReplayBroadcast.liveReplayHandle = this;
        liveReplayBroadcast.setToggleHandle(this);
    }

    @Override
    public void onBackPressed() {
        if (programView != null && programView.getParent() != null) {
            showAnimation.cancel();
            ViewGroup parent = (ViewGroup) programView.getParent();
            parent.removeView(programView);
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void initView() {
        super.initView();
//        showAnimation = AnimationUtils.loadAnimation(this, R.anim.show_audio_program_animation);
    }

   /* @Override
    protected void initHalfScreenView() {

        super.initHalfScreenView();
        TextView textView = Utility.findViewById(mRootView, R.id.tv_live_statue);
        textView.setVisibility(View.GONE);
        //currentPlayPosition.setVisibility(View.GONE);
        //  totoalLength.setVisibility(View.GONE);
    }*/

    @Override
    protected List<View> getPaidViews() {
        List<View> list = new ArrayList<>();
        list.add(seekbar);
        return list;
    }

    protected void getAudioDetail() {
        if (isFinish)
            return;
        String navigate_id = catalogItem != null ? catalogItem.getCatid() : "";
        newsDetailInvoker.getArticleById("" + articleItem.getId(),  navigate_id);
    }

    protected void getProgramList() {
        if (programListCallBack == null) {
            programListCallBack = new ProgramListCallBack();
            liveProgramListInvoker = new VideoLiveProgramListInvoker(programListCallBack);
        }
        liveProgramListInvoker.getLiveVideoProgramList(articleItem);
    }

    class ProgramListCallBack implements DataInvokeCallBack<LiveProgramListReciver> {
        @Override
        public void success(LiveProgramListReciver data) {
            programListItems = data.programListItems;
            if (programListItems == null) {
                programListItems = new ArrayList<>();
            }
            if (programListItems.size() == 0) {
                ToastUtil.showCustomView(AudioLiveDetailActivityHalf.this, R.string.no_audioprogramlist);
                return;
            }
            if (audioLiveProgramTable != null)
                audioLiveProgramTable.success(data);
            showStreamLine();
        }

        @Override
        public void fault(Object data) {
            if (programListItems == null) {
                programListItems = new ArrayList<>();
            }
            Log.w(TAG, "get audio live programlist failed:" + data);
            showStreamLine();
        }
    }

    @Override
    public void handleItem(ProgramListItem item) {
        try {

            if (GuideItemState.REPLAY == ProgramListItem.getItemState(item)) {
                //给他置个标记
                Date startDate = DateParse.parseDate(item.getStarttime(), null);
                Date endDate = DateParse.parseDate(item.getEndtime(), null);
                AuthMode mode = URLAuth.EncrptMode(cdnEncrypt, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_key, AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.vms_cdn_iv);
                startLong = startDate.getTime();
                endLong = endDate.getTime();
                liveMediaPlayBackInvoker.getLiveUrlPlayBackUrl(url, mode != null ? mode.getCode() : "", startLong, endLong);
            } else if (GuideItemState.LIVE == ProgramListItem.getItemState(item)) {
                startLong = 0L;
                endLong = 0L;
                apsKit.resetSourceAndPlayer();
                startPlay(url, articleItem);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void startPlay(String url, ArticleItem articleItem) {
        MusicEntity entity = new MusicEntity(articleItem.getTitle(),url);
        entity.setAlbum("");
        entity.setSinger("");
        apsKit.setData(entity);
    }



    @Override
    public void onToggleClick() {

    }

    //直播显示节目单
    @Override
    protected void showStreamLine() {
        initAnimation();
        if (programListItems == null) {
            ToastUtil.showCustomView(this, R.string.isinvoke_audioprogramlist);
            initProgramList();
            showOrHide();
        } else if (programListItems.size() == 0) {
            ToastUtil.showCustomView(this, R.string.no_audioprogramlist);
        } else {
            showOrHide();
        }

    }

    class LivePlayBackUrlReciver implements DataInvokeCallBack<BaseMessageReciver> {

        @Override
        public void success(BaseMessageReciver data) {
            Log.w(TAG, "LivePlayBackUrlReciver success");
            if (data.state) {
                JSONObject reciveData = data.orginData.optJSONObject("data");
                if (reciveData != null && !TextUtils.isEmpty(reciveData.optString(LiveMediaPlayBackInvoker.Url))) {
                    String url = reciveData.optString(LiveMediaPlayBackInvoker.Url);
                    apsKit.resetSourceAndPlayer();
                    startPlay(url, articleItem);
                } else {
                    ToastUtil.show(AudioLiveDetailActivityHalf.this, R.string.getplaybackurlerror);
                }
            }
        }


        @Override
        public void fault(Object data) {
            Log.w(TAG, "LivePlayBackUrlReciver fault");
            ToastUtil.show(AudioLiveDetailActivityHalf.this, R.string.getplaybackurlerror);
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {
            AcquisitionManager.getInstance().readEnter(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        UserInfo info = UserInfo.getUserInfo(this);
        if (articleItem != null) {

            AcquisitionManager.getInstance().readExit(info, "" + articleItem.getId(),
                    DomainUtil.getDomain(articleItem.getUrl()), articleItem.getUrl(), articleItem.getTitle(), articleItem.getContent());
        }
    }

    private Float dp2px(Context context, int dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (dpValue * scale + 0.5f);
    }

    @Override
    public void noNetwork() {
        mErrorView.setVisibility(View.VISIBLE);
        emptyTipsText.setText("网络请求失败，请点击重试");
        mErrorView.setOnClickListener(v -> {
            if (hasNetWork)
                getAudioDetail();
            else showNetWorDialog();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}